package com.retry.task.admin.infrastructure.scheduler;

import java.util.List;
import java.util.function.Consumer;

import javax.annotation.Resource;

import com.retry.task.admin.infrastructure.lock.ILock;
import com.retry.task.admin.biz.service.RetryTaskGroupBizService;
import com.retry.task.admin.biz.service.RetryTaskLogBizService;
import com.retry.task.admin.biz.service.RetryTaskBizService;
import com.retry.task.admin.dal.model.query.RetryTaskQuery;
import com.retry.task.core.model.RetryTaskDTO;
import com.retry.task.core.model.base.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/5/13  14:34
 * @Description TODO
 */
public abstract class BaseScheduler implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseScheduler.class);

    @Autowired
    protected RetryTaskBizService retryTaskService;

    @Autowired
    protected RetryTaskLogBizService retryTaskLogService;

    @Value("${envirment.isTest}")
    protected Integer isTest;
    @Autowired
    protected TransactionTemplate centerTransactionTemplate;



    @Autowired
    protected ILock mysqlLock;

    @Resource
    protected RetryTaskGroupBizService retryTaskGroupService;

    protected void processTask(RetryTaskQuery query, Consumer<List<RetryTaskDTO>> consumer) {
        int pageNum = 1;
        while (true) {
            query.setPageNum(pageNum);
            PageResult<List<RetryTaskDTO>> pageResultDTO = retryTaskService.queryRetryTask(query);
            if (!pageResultDTO.isSuccess()) {
                LOGGER.error("[[RetryTaskProcessor-queryTetryTask]] query retry task error,{}",
                    pageResultDTO.getErrMsg());
                break;
            }
            List<RetryTaskDTO> retryTaskDTOS = pageResultDTO.getData();
            if (CollectionUtils.isEmpty(retryTaskDTOS)) {
                break;
            }
            consumer.accept(retryTaskDTOS);
            if (retryTaskDTOS.size() < query.getPageSize()) {
                break;
            }
            pageNum++;
        }
    }
}
